#!/bin/bash

# 设置默认参数
ARCH=${1:-"amd64"}
XINFANG_IMAGE="xinfang:latest"

# 切换到项目目录
cd "$(dirname "$0")"
ROOT=$(pwd)

echo "===== 开始部署 xinfang 应用 (架构: ${ARCH}) ====="

# 检查镜像文件是否存在
XINFANG_IMAGE_FILE="${ROOT}/images/xinfang-api-linux_${ARCH}.tar.gz"

if [ ! -f "${XINFANG_IMAGE_FILE}" ]; then
    echo "错误: xinfang 镜像文件不存在: ${XINFANG_IMAGE_FILE}"
    echo "请先构建 xinfang 镜像"
    exit 1
fi

# 检测使用 docker compose 还是 docker-compose
if command -v docker-compose &> /dev/null; then
    COMPOSE_CMD="docker-compose"
else
    COMPOSE_CMD="docker compose"
fi

${COMPOSE_CMD} -f "${COMPOSE_FILE}" down
# 加载镜像前先卸载老的镜像
echo "卸载旧的 xinfang 镜像 (${ARCH})..."
docker rmi "${XINFANG_IMAGE}" 2>/dev/null || true

# 加载新的镜像
echo "加载 xinfang 镜像 (${ARCH})..."
docker load < "${XINFANG_IMAGE_FILE}"
if [ $? -ne 0 ]; then
    echo "加载 xinfang 镜像失败!"
    exit 1
fi

COMPOSE_FILE="${ROOT}/docker-compose.yml"

# 启动服务
echo "启动 xinfang 服务..."
${COMPOSE_CMD} -f "${COMPOSE_FILE}" up -d

if [ $? -eq 0 ]; then
    echo "===== xinfang 应用部署成功 ====="
    echo "请检查 docker-compose.yml 中配置的服务端口"
else
    echo "===== xinfang 应用部署失败 ====="
fi
